<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\AdminTenant\Action\Admin;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Tenant\Contract\TenantContract;
use MoChat\App\User\Contract\UserContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;

/**
 * 租户管理- 创建提交.
 *
 * Class Show.
 * @Controller
 */
class Show extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var TenantContract
     */
    protected $tenantService;

    /**
     * @Inject
     * @var UserContract
     */
    protected $userService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    private $logger;

    /**
     * @RequestMapping(path="/admin/tenant/show", methods="get")
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @return array 返回数组
     */
    public function handle(): array
    {
        # # 参数验证
        $this->validated($this->request->all());
        $adminUser = user();

        # # 接收参数
        $id = (int) $this->request->input('id');
        $info = $this->tenantService->getTenantById($id, ['id', 'name', 'status', 'company_name', 'business_image', 'area', 'description', 'max_employee', 'max_corp', 'sku_id', 'role_menu', 'root_id']);
        if (! empty($info['businessImage'])) {
            $businessImage = Json::decode($info['businessImage']);
//            foreach ($businessImage as &$item) {
//                $item = file_full_url($item);
//            }
            $info['businessImage'] = $businessImage[0];
            $info['fullBusinessImage'] = file_full_url($businessImage[0]);
        }
        $user = $this->userService->getUserById($info['rootId'], ['phone']);
        $info['phone'] = $user['phone'] ?? '';
        return $info;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
            'id' => 'required | integer | bail',
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
            'id.required' => 'id 必填',
            'id.integer' => 'id 必需为整数',
        ];
    }
}
